/**
 * Created by 黄敏 on 2016/10/17.
 */

!function () {
    //定义css
    var style =
        ".nowrapbr{" +
        "white-space:nowrap !important;" +
        "}" +

        ".nowrapbr br{" +
        "display:none ;" +
        "}" +

        "#readbook-create,#readbook-calculate,readbook-calculate *,#readbook-create *{ " +
        "-webkit-box-sizing: border-box; " +
        "-moz-box-sizing: border-box;" +
        "box-sizing: border-box;" +
        "}" +

        "#readbook-create img,#readbook-calculate img{" +
        "max-width:100%;" +
        "height:auto !important;" +
        "max-height:100% !important" +
        "}" +
        "#book-loading{" +
        "position: fixed;" +
        "width:100%;" +
        "height:100%;" +
        "background:#f3f1e9;" +
        "z-index: 100;" +
        "text-align: center;" +
        "display: none;" +
        "}" +
        "#book-loading .book-loading{" +
        "width:100%;" +
        "height:100%;" +
        "position: fixed;" +
        "top:30%;" +
        "color:#444;" +
        "}" +
        ".button-tautology{" +
        "padding:5px 20px;" +
        "margin-top:54px;" +
        "border:1px solid #aaa;" +
        "text-decoration: none;" +
        "color:#333;" +
        "}" +
        ".loadimg-error-next{" +
        "margin-right:10px;" +
        "margin-top:5px;" +
        "}";

    $('<style>' + style + '</style>').appendTo('head');
}();


(function ($) {
    $.fn.readBook = function (callbacks) {
        var goBack = {
                hasRead: false
            },
            _this = this,
            datas = {
                contents: [],       //未分页内容 已标记段落
                paging: [],         //分页内容
                chapting: [],       //分章内容
                nowChapter: 0,      //当前章节
                nowparagraph: 0,    //当前段落，0为封面
                nowpage: 0,         //当前第几页
                catalog: [],        //目录列表
                book: [],           //书的详细
                cookieName: 'common',   //书的cookie名
                reading: Object.create(null) || {},      //正在读的数据
                isPageMode: true,   //默认翻页模式
                isquestion: true,   //问题首次需要加载
                fontSize: 1.3,
            },
            local = {
                bookData: null,
                chapterData: null,
                url:null
            }

        var fS = $.cookie('fontsize');  //查看cookie设定的字体
        if (fS) {
            datas.fontSize = parseFloat(fS);
        }

        _this.timeout = new Date().getTime(); //超时时间

        var bookId = getSearch('id');
        local.url = getSearch('localurl');




        /************************返回的对象*****************/
        //选择章节
        goBack.selectChapter = function (index, callback) {
            startLoad();
            setTimeout(function(){
            if (!datas.contents[index]) {
                datas.nowChapter = index;
                getBookChapter(datas.catalog[datas.nowChapter].id, datas.nowChapter, function () {
                    location.hash = '#' + datas.catalog[datas.nowChapter].id;
                    datas.nowpage = 0;
                    _this.readBook.html(datas.paging[datas.nowChapter][datas.nowpage]);
                    setCooking(); //正在阅读
                    endLoad();
                    callback()
                });
            } else {

                datas.nowChapter = index;
                datas.nowpage = 0;

                _this.readBook.html(datas.paging[datas.nowChapter][datas.nowpage]);
                setCooking(); //正在阅读
                endLoad();
                callback()
            }
            },300)
        };

        goBack.getPageData = function () {

            return {
                chapterName: datas.catalog[datas.nowChapter].title,
                pageNum: datas.nowpage + 1,
                pageCount: datas.paging[datas.nowChapter].length,
                nowChapter: datas.nowChapter,
                fontSize: datas.fontSize
            }

        };

        //下一页
        goBack.nextPageFun = function (callback) {

            if (!timeoutFun(500)) return false; //间隔500毫秒才向下执行

            if (datas.nowpage < datas.paging[datas.nowChapter].length - 1) {  //当前页少于当前章节总页数时

                datas.nowpage += 1; //页数加1

                nextAnimate(datas.paging[datas.nowChapter][datas.nowpage]);

                setTimeout(function () {
                    //最后一页时，加载下一章内容
                    if (datas.nowpage == datas.paging[datas.nowChapter].length - 1 && !datas.contents[datas.nowChapter + 1]) {
                        getBookChapter(datas.catalog[datas.nowChapter + 1].id, datas.nowChapter + 1, function () {
                            console.log('新章节加载成功');
                        });
                    }
                }, 350);
                callback()
            } else {

                //最后一页再翻下一页，翻到下一章节
                if (datas.nowChapter < datas.catalog.length - 1) {
                    if (!datas.contents[datas.nowChapter + 1]) {
                        startLoad();
                        getBookChapter(datas.catalog[datas.nowChapter + 1].id, datas.nowChapter + 1, function () {
                            endLoad();
                            nextChapterFun();
                            callback()
                        });
                    } else {

                        nextChapterFun();
                        callback()
                    }
                }
            }

            setCooking(); //正在阅读
        };


        //上一页
        goBack.prevPageFun = function (callback) {


            if (!timeoutFun(500)) return false; //间隔500毫秒才向下执行

            //翻书模式
            if (datas.nowpage > 0) {
                datas.nowpage -= 1;

                prevAnimate(datas.paging[datas.nowChapter][datas.nowpage]); //上一页动画

                setTimeout(function () {
                    if (datas.nowpage === 0 && datas.nowChapter > 0 && !datas.contents[datas.nowChapter - 1]) {
                        getBookChapter(datas.catalog[datas.nowChapter - 1].id, datas.nowChapter - 1, function () {
                            console.log('上一章加载成功');
                        });
                    }
                }, 350);
                callback()
            } else {

                if (datas.nowChapter > 0) {

                    if (!datas.contents[datas.nowChapter - 1]) {
                        console.log('没数据');
                        startLoad();
                        getBookChapter(datas.catalog[datas.nowChapter - 1].id, datas.nowChapter - 1, function () {
                            endLoad();
                            prevChapterFun();
                            callback()
                        });
                    } else {
                        console.log('有数据');
                        prevChapterFun();
                        callback()
                    }
                }
            }

            setCooking(); //正在阅读
        };

        //修改字号
        goBack.ModFontSize = function (num) {
            startLoad();
            setTimeout(function () {
                $.cookie('fontsize', num);
                datas.fontSize = num;
                _this.readBook.css('font-size', num + 'em');
                _this.calculate.css('font-size', num + 'em');

                _this.calculate.find('.pager-inner').html(datas.contents[datas.nowChapter]);
                addParagraphData(_this.calculate.find('.pager-inner>*'), datas.nowChapter);
                doPaging(datas.nowChapter); //排好的内容
                paragraphToPage();//判断章节在哪一页
                console.log(datas.paging);
                _this.readBook.html(datas.paging[datas.nowChapter][datas.nowpage].clone());//初始章节初始页写入;
                callbacks({book: datas.book, catalog: datas.catalog},goBack);
                endLoad()
            }, 100);

        };
        /************************返回的对象*****************/
        loader(); //初始化加载框
        startLoad();

        $.ajax({
            url: local.url+bookId+'/list.cache',
            success: function(data){
                local.bookData = data;  //查看是否有本地文件
                getDownTo();
            },
            error:function(){
                console.log('本地文件不存在');
                getDownTo();
            },
            dataType: 'json'
        });





        function getDownTo (){
        getBook(bookId, function (data) {

            datas.cookieName = 'bookid' + data.book.id;
            datas.catalog = data.cata;
            datas.book = data.book;  //书籍简要

            getCookie(); //查询cookie,并更改默认的章节和段落位置

            create_reading_condition(); //创建阅读环境

            //获得章节内容
            getBookChapter(datas.catalog[datas.nowChapter].id, datas.nowChapter, function () {
                paragraphToPage();//判断章节在哪一页
                _this.readBook.html(datas.paging[datas.nowChapter][datas.nowpage].clone());//初始章节初始页写入;
                console.log(datas);
                callbacks({book: datas.book, catalog: datas.catalog},goBack);
                endLoad();

            });

        });
        }
        /*****************************************************函数**************************************************************/

        /*获取url上的查询字串,str = 参数名称，如ID,CID,name*/
        function getSearch(str) {
            var str1 = null;
            if(str =='id'){
                str1 = new RegExp(str + '\\D(\\d+)');
            }else{
                str1 = new RegExp(str + '\\D([^&]+)');
            }
            var href = str1.exec(location.href);
            var id = href && href[1];

            if(str =='id') {
                if (!id) {
                    alert('你输入的网址有误！');
                    return location.href = '/jingdian/';
                }
            }
            return id;
        }

        //获取书本信息
        function getBook(bookid, callBack) {
            loading('加载目录数据 10%');
            console.log(bookid);
            if (!local.bookData) {
                $.ajax({
                    'data': 'get',
                    'url': 'http://www.askingdao.com/Readbook/getCatalogue',
                    'data': {"bookid": bookid},
                    'success': cataAdd,
                    'typeData': 'jsonp',
                    'error':ajaxError
                });

            } else {
                console.log('数据已经存在！，由本地获得');
                cataAdd(local.bookData)
            }

            function cataAdd(data) {
                data.cata.unshift({
                    bookid: 0,
                    id: 0,
                    title: '封面/简介'
                });

                data.cata.push({
                    bookid: 999999,
                    id: 999999,
                    title: '本书完'
                });
                callBack(data);
            }
        }

        function getCookie() {

            //描点章节
            var hash = location.hash;
            console.log('描点', /#/.test(hash));

            if (/#/.test(hash)) {

                var cap = hash.slice(1);
                if (!isNaN(cap)) {

                    for (var i = 0; i < datas.catalog.length; i++) {

                        if (datas.catalog[i].id == cap) {
                            datas.nowChapter = parseInt(i);   //更改默认当前章节
                            datas.nowparagraph = 0;
                            console.log('描点更改默认章节为' + i);
                            break;
                        }
                    }

                }

            } else {

                //cookie章节
                var cookieName = $.cookie(datas.cookieName);
                var cookieVertical = $.cookie('isvertical');

                //cookie为空时，不用eval

                var data = cookieName && eval('(' + cookieName + ')');
                var isVertical = cookieVertical && eval('(' + cookieVertical + ')');

                if (typeof isVertical === 'boolean') {
                    datas.isPageMode = isVertical;
                }


                console.log('cookie-data:' + JSON.stringify(data));
                // data = {"chapter": 389, "paragraph": 0};
                // console.log('测试，修改cookie-data为:' + JSON.stringify(data));
                console.log('cookie-isVertical:' + isVertical);

                if (data) {
                    for (var i = 0; i < datas.catalog.length; i++) {

                        if (datas.catalog[i].id == data.chapter) {
                            datas.nowChapter = parseInt(i);   //更改默认当前章节
                            console.log('cookie更改默认章节为' + i);
                            break;
                        }
                    }

                    if (data.paragraph != null) {
                        datas.nowparagraph = parseInt(data.paragraph);  //更改默认段落
                        console.log('cookie更改默认段落为' + data.paragraph);
                    }

                    //定位上次阅读提示
                    if (datas.nowparagraph > 0 || datas.nowChapter > 0) { //定位的位置不是在第一页时，定位到上次阅读

                        console.log('启用 上次阅读 goBack.hasRead = true;');
                        goBack.hasRead = true;
                        return
                    }

                    console.warn('在第一页，不启用 “上次阅读”');

                }
            }

        }

        //创建阅读环境
        function create_reading_condition() {
            _this.readBook = $('<div></div>', {
                id: 'readbook-create',
                style: ' position: relative;' +
                'width:200%;' +
                'height:100%;' +
                'font-size:' + datas.fontSize + 'em'
            });
            _this.calculate = _this.readBook.clone().attr('id', 'readbook-calculate').css({'visibility': 'hidden'});
            _this.append(_this.readBook);
            _this.append(_this.calculate);

            console.log('创建阅读环境成功');
        }


        //获取章节信息
        function getBookChapter(id, indexs, callBack) {

            loading('加载章节数据 50%');

            var index = indexs;


            $.ajax({
                url: local.url+datas.book.id+'/'+id+'.cache',
                success: function(data){
                    local.chapterData = data;  //查看是否有本地文件
                    getBookChapterSecondStep();
                },
                error:function(){
                    console.log('本地章节文件不存在');
                    getBookChapterSecondStep();
                },
                dataType: 'json'
            });

            function getBookChapterSecondStep(){
                if (index == 0) {
                    console.warn('章节定位是第一页，跳过章节内容查询', index);
                    getBookChapter_next(createCover());

                } else if (index == datas.catalog.length-1) {

                    console.warn('章节定位是最后一页，跳过章节内容查询');
                    getBookChapter_next(createEnd());

                } else if (local.chapterData) {

                    console.log('该章节用本地数据');
                    bookChapterData(local.chapterData);

                } else {

                    console.log('章节定位不是第一页或最后一页，查询章节数据');
                    console.log('章节ID是', id);
                    $.ajax({
                        'type': 'get',
                        'url': 'http://www.askingdao.com/Readbook/getbookcontent',
                        'data': {id: id},
                        'success': bookChapterData,
                        'typeData': 'jsonp',
                        'error':ajaxError
                    });

                }
            }

            function bookChapterData(data) {
                var da = data.content.replace(/font-size:\s?\d+px;/gi, '');
                var content = createChapterName(index) + da; //章节页+章节内容
                local.chapterData = null;
                data = null;
                getBookChapter_next(content);
            }


            function getBookChapter_next(content) {

                var wrapContent = htmlWrap(content); //内容穿外套

                //判断计算框是否已经创建
                _this.calculate.empty().html(wrapContent);  //内容放入计算框内

                var loadImg = _this.calculate.find('img');
                console.time('加载图片');
                if (loadImg.length > 0) {
                    var num = 0;
                    var onloads = function () {  //等待图片加载完成

                        num++;
                        loading('加载图片' + num + '/' + loadImg.length + ' 80%');
                        if (num === loadImg.length) {
                            console.timeEnd('加载图片');
                            console.log('图片加载完成');
                            addParagraphData(_this.calculate.find('.pager-inner>*'), index);
                            init(index)
                        }

                    };

                    for (var i = 0; i < loadImg.length; i++) {
                        loadImg.get(i).onload = onloads;
                    }
                    var errorimg = 0;
                    loadImg.on('error',function(){
                        loading('本章'+(++errorimg)+'张图片丢失(共'+loadImg.length+'张)，是否继续阅读<br>' +
                            '<button class="loadimg-error-next">继续阅读</button>' +
                            '<a href="http://www.askingdao.com/jingdian/" style="text-decoration: none">退出</a>');

                        $('.loadimg-error-next').one('touchend',function(){
                            addParagraphData(_this.calculate.find('.pager-inner>*'), index);
                            init(index);
                            return false;
                        })
                    })

                } else {
                    addParagraphData(_this.calculate.find('.pager-inner>*'), index);
                    init(index);
                }

                function init(num) {
                    doPaging(num); //排好的内容
                    callBack();
                }
            }
        }


        //创建封面
        function createCover() {
            var cover = '<p id="book_cover_page" class="newpage" data-nowparagraph="-3" style="height:100%;text-align: center">' +
                '<img style="height:100%" src="' + datas.book.titlepic + '" alt=""></p>';
            var intro = '<p  id="book_intro_page" data-nowparagraph="-2">【简介】</p><p class="newpage">' + datas.book.description + '</p>';

            return cover + intro;
        }

        //创建最后一页
        function createEnd() {

            var style = 'style="text-align:center;position:relative;padding-top:50%;font-size:1.5em;line-height:1.2"';
            var ChapterName = '<h3 class="ChapterName newpage" data-nowparagraph="-4" ' + style + '>（<span>' + datas.nowChapter + '</span>）<br>本书完</h3>';
            return ChapterName;
        }

        //创建章节页
        function createChapterName(da) {

            var style = 'style="text-align:center;position:relative;padding-top:50%;font-size:1.5em;line-height:1.2"';
            var ChapterName = '<h3 class="ChapterName newpage" data-nowparagraph="-1" ' + style + '>（<span>' + da + '</span>）<br>' + datas.catalog[da].title + '</h3>';
            return ChapterName;
        }

        //创建阅读环境内部
        function htmlWrap(content) {
            var pagerWrap = $('<div></div>', {
                class: 'readbook-pager-wrap',
                style: 'position:relative;' +
                'overflow:hidden;' +
                'float:left;' +
                'padding:15px 10px;' +
                'width:50%;' +
                'height:100%;' +
                'font-family:"Times New Roman","宋体",HELVETICA;' +
                'font-size:1em;' +
                'line-height:1.8em',
                html: '<div class="readbook-pager" style="position: relative;height:100%;overflow:hidden;margin:5px auto 5px;">' +
                '<div class="pager-inner" style="overflow: hidden">' + content + '</div></div>'
            });
            return pagerWrap.clone();
        }

        //添加段落data
        function addParagraphData(allThis, index) {
            loading('分析段落数据 90%');
            var arr = [];
            allThis.each(function (index, val) {

                var obj = $(val); //拿到一个段落

                var mTop = parseFloat(obj.css('margin-top'));
                var mBottom = parseFloat(obj.css('margin-bottom'));

                var tagData = {
                    margin: mTop >= mBottom ? mTop : mBottom,
                    outerHeight: obj.outerHeight(true)
                };

                if (obj.find('br:only-child').length == 0) {
                    obj.addClass('nowrapbr');
                }

                if (allThis.eq(index + 1).find('br:only-child').length == 0) {
                    allThis.eq(index + 1).addClass('nowrapbr');
                }

                var attr = {
                    'data-height': tagData.outerHeight,
                    'data-margin': tagData.margin,
                    'data-singleheight': obj.height(),
                    'data-nowparagraph': index,
                    'data-nextsingleheight': allThis.eq(index + 1).height()
                };

                obj.attr(attr);

                allThis.eq(index + 1).removeClass('nowrapbr');
                obj.removeClass('nowrapbr');
                arr.push(obj.clone());
            });

            datas.chapting[index] = allThis.clone();
            console.log('章节数据已写入(datas.chapting)');
            datas.contents[index] = arr;
            console.log('章节段落数组数据已写入(datas.contents)');

            console.log('为段落添加数据成功');
        }


        //分页操作
        function doPaging(index) {
            loading('计算页面数量 99%');
            console.time('分页操作');
            var pageH = _this.calculate.find('.readbook-pager-wrap').height(),
                gatherContent = [],
                arrInde = 0,
                initHeight = 0,
                hiddenValue = 0, //最后一段未显示部分
                showValue = 0, //最后一段显示部分
                conThis = datas.contents[index], //内容段落数组
                vessel = $([]),
                Paragraphs = [];

            for (var i = 0; i < conThis.length; i++) {
                Paragraphs.push(conThis[i].data('nowparagraph')); //段落编号

                textPage(conThis[i], i);

                if (i === conThis.length - 1) {
                    console.timeEnd('分页操作');
                }

            }

            datas.paging[index] = gatherContent;

            //计算页面函数
            function textPage(thisOjbs, thisNum) {
                var i = parseInt(thisNum),
                    thisOjb = thisOjbs,
                    pageH2 = pageH + showValue;

                vessel = vessel.add(thisOjb);  //把元素放到容器

                var marginTop = thisOjb.data('margin');   //元素的marin值
                var singleheight = thisOjb.data('singleheight'); //当前单行高度
                // console.log('单行高度' + (singleheight));
                var nextsingleheight = thisOjb.data('nextsingleheight') !== null ? thisOjb.data('nextsingleheight') : 0; //下一个单行高度

                var height = thisOjb.data('height') - marginTop;  //元素总高度，相邻的margin会重叠，所以减一个margintop
                var minSize = marginTop + nextsingleheight;  //页面底空最少高度

                if (singleheight == 0) {
                    return false;
                }

                initHeight += height;  //累加高度,相邻的margin会重叠，所以减一个margintop;

                if (initHeight + marginTop <= pageH2) {    //累加高度与文本容器高度对比


                    if (initHeight + minSize > pageH2 || conThis.length === i + 1 || thisOjb.hasClass('newpage')) {

                        // console.log('第' + (arrInde + 1) + '页');

                        if (conThis.length === i + 1) {
                            // console.log('最后一页');
                            initHeight += 20;
                        }

                        // if (thisOjb.hasClass('newpage')) {
                        //     console.log('有标注另起一页');
                        //
                        // }

                        gatherContent[arrInde] = vessel.wrapAll(htmlWrap('')).closest('.readbook-pager-wrap').clone();

                        gatherContent[arrInde].attr('data-Paragraphs', Paragraphs);

                        Paragraphs = [];
                        if (showValue > 0) {  //判断前一页，未显示的高度
                            var innerCss = {
                                'margin-top': -(showValue) + 'px',
                                'height': initHeight
                            }
                            hiddenValue = 0;
                        } else {
                            var innerCss = {
                                'height': initHeight
                            }

                        }


                        if (!thisOjb.hasClass('newpage')) {
                            gatherContent[arrInde].find('.pager-inner').css(innerCss);
                        }

                        showValue = 0;
                        arrInde += 1;     //数组索引加1
                        initHeight = 0;   //累加高度归0
                        vessel = $([]);   //容器清空
                    }

                } else {

                    // if (initHeight - height == 0) {
                    //     singleheight = singleheight
                    // }

                    gatherContent[arrInde] = vessel.wrapAll(htmlWrap('')).closest('.readbook-pager-wrap').clone();
                    gatherContent[arrInde].attr('data-Paragraphs', Paragraphs);
                    Paragraphs = [];
                    var showValue2 = showValue;

                    showValue = Math.floor((pageH2 - initHeight + height - marginTop * 2) / singleheight) * singleheight + marginTop; //最后一段显示部分

                    hiddenValue = height - showValue;

                    // console.log('第' + (arrInde + 1) + '页,分页后，有' + hiddenValue + '未显示');

                    if (parseInt(showValue) <= marginTop) {
                        showValue = 0;
                    }
                    var cssStyle = {
                        'height': initHeight - height + showValue,
                        'margin-top': -(showValue2) + 'px',
                    }

                    //处理满屏图片放不下的问题
                    if (pageH2 < singleheight + marginTop * 2) {
                        cssStyle.height = pageH2;
                        gatherContent[arrInde].find('.pager-inner p *').css({
                            'height': pageH2 - marginTop * 2,
                            'width': 'auto'
                        });
                    }

                    gatherContent[arrInde].find('.pager-inner').css(cssStyle);
                    arrInde = arrInde + 1;     //数组索引加1
                    initHeight = 0;   //累加高度归0
                    vessel = $([]);   //容器清空

                    if (pageH2 > singleheight + marginTop * 2) {

                        textPage(thisOjb, i);
                    }
                }
            }
        }

        //计算段落所在哪一页
        function paragraphToPage() {
            datas.paging[datas.nowChapter].forEach(function (val, i) {

                var par = val.data('paragraphs').toString().split(',');

                if ($.inArray(datas.nowparagraph.toString(), par) !== -1) {
                    datas.nowpage = parseInt(i);
                }
            });

        }

        //计时器
        function timeoutFun(time) {

            var timeout2 = new Date().getTime();

            if (timeout2 - _this.timeout < time) {
                return false;
            } else {
                _this.timeout = timeout2;
                return true;
            }
        }



        //下一页过渡动画
        function nextAnimate(data) {
            var child = _this.readBook.children();
            _this.readBook.append(data.clone());
            _this.readBook.animate({'left': '-100%'}, 400, function () {
                child.remove();
                _this.readBook.css('left', '0');
            });
        }

        //下一章节
        function nextChapterFun() {
            datas.nowChapter += 1;
            datas.nowpage = 0;
            location.hash = '#' + datas.catalog[datas.nowChapter].id;
            console.log('datas.nowChapter', datas.nowChapter);
            nextAnimate(datas.paging[datas.nowChapter][datas.nowpage]);
        }




        //上一页过渡动画
        function prevAnimate(data) {
            var child = _this.readBook.children();
            _this.readBook.prepend(data.clone());
            _this.readBook.css('left', '-100%');
            _this.readBook.animate({'left': '0%'}, 400, function () {
                child.remove();
            });
        }

        //上一章节
        function prevChapterFun() {
            datas.nowChapter -= 1;
            location.hash = '#' + datas.catalog[datas.nowChapter].id;
            console.log(datas.paging[datas.nowChapter]);
            datas.nowpage = datas.paging[datas.nowChapter].length - 1;
            prevAnimate(datas.paging[datas.nowChapter][datas.nowpage]);

        }


        //正在阅读
        function setCooking() {

            var par = datas.paging[datas.nowChapter][datas.nowpage].data('paragraphs').toString().split(',');

            if (!par[0]) {
                par = datas.paging[datas.nowChapter][datas.nowpage - 1].data('paragraphs').toString().split(',');
                if (!par[par.length - 1]) {
                    par = datas.paging[datas.nowChapter][datas.nowpage - 2].data('paragraphs').toString().split(',');
                    datas.reading.pid = par[par.length - 1];
                } else {
                    datas.reading.pid = par[par.length - 1];
                }

            } else {
                datas.reading.pid = par[0];
            }
            setCookie(datas.catalog[datas.nowChapter].id, datas.reading.pid);
        }

        //记录cookie
        function setCookie(chapter, paragraphid) {
            datas.nowparagraph = paragraphid;
            $.cookie(datas.cookieName, '{chapter:' + chapter + ',paragraph:' + (paragraphid || 0) + '}', {expires: 9999});
            $.cookie('isvertical', (datas.isPageMode ? 'true' : 'false'), {expires: 9999});
            console.log('修改Cookie为：', $.cookie(datas.cookieName))
        }

        //加载框
        function loader() {
            _this.bookLoading = $('<div></div>', {
                id: 'book-loading',
                html: '<div class="book-loading"> ' +
                '<img src="" alt="加载中..."><br> ' +
                '<span class="loading-info">正在很卖力的处理中^_^~~</span> <br>' +
                '<span class="loading-detail"></span>' +
                '</div>'
            });

            $('body').append(_this.bookLoading);
        }

        //开始加载
        function startLoad() {
            _this.bookLoading.fadeIn(100);
            _this.bookLoading.find('span.loading-detail').html('');
        }

        //加载中
        function loading(val) {
            _this.bookLoading.find('span.loading-detail').html(val);
        }

        //加载完毕
        function endLoad() {
            _this.bookLoading.fadeOut(100);
        }

        //ajax请求错误
       function ajaxError(){
            console.log('加载失败');
            loading('<span style="color:orangered">加载失败，请检查网络</span> <br><br><a class="button-tautology" href="javascript:location.reload(true)">重试</a> <a  class="button-tautology" href="http://www.askingdao.com/jingdian/">退出</a>')
        };

        /*****************************************************函数**************************************************************/
        return goBack;
    };
})(jQuery);